# coding=utf-8

# useage:
#
#   python build-ios.py trunk inhouse 3.3.0 com.wanmei.mini.condorapp.temp (打包某个渠道)
#
#   python build-ios.py all inhouse 3.3.0   (打所有渠道，bundleid使用默认配置)
#

import os
import sys

# 设置签名信息
signs = {'inhouse':("iPhone Distribution: Tianjin Ledo Interactive Technology Co., Ltd.", "d0c175b5-c09f-4cf0-a4d2-350bfb1fcb6c", "sdmini branch inhouse"),
         'dis':("iPhone Distribution: Tianjin Ledo Interactive Technology Co., Ltd.", "d0c175b5-c09f-4cf0-a4d2-350bfb1fcb6c", "sdmini branch inhouse"),
         'dev':("iPhone Distribution: Tianjin Ledo Interactive Technology Co., Ltd.", "d0c175b5-c09f-4cf0-a4d2-350bfb1fcb6c", "sdmini branch inhouse")
         }

# 设置渠道plist文件相对路径
plists = {"trunk":("KnightClient", "./KnightClient/KnightClient_Info.plist"),
          "uc":("KnightClient_uc","./KnightClient/KnightClient_Infouc.plist")
          }


def build_target(nickname, target, sign_info, cur_plist, version, bundleid=None):
    cur_xcarchive = "./" + nickname + ".xcarchive"
    cur_ipa = "./" + nickname + ".ipa"

    # clean project
    if os.path.isfile(cur_ipa):
        os.remove(cur_ipa)
    if os.path.isfile(cur_xcarchive):
        os.remove(cur_xcarchive)

    # set version
    print "正在设置版本号(" + version + ")..."
    os.system("/usr/libexec/PlistBuddy -c \"Set:CFBundleShortVersionString " +  version + "\" \"" + cur_plist + "\"")
    os.system("/usr/libexec/PlistBuddy -c \"Set:CFBundleVersion " +  version + "\" \"" + cur_plist + "\"")

    # create .xcarchive
    print ("正在生成xcarchive文件...")
    str_create_xcarchive = "xcodebuild -scheme \"" + target + "\" " + "archive -archivePath \"" + cur_xcarchive + "\" "
    str_create_xcarchive += "CODE_SIGN_IDENTITY=\"" + sign_info[0] + "\" "
    str_create_xcarchive += "PROVISIONING_PROFILE=\"" + sign_info[1] + "\" "
    if bundleid is not None:
        str_create_xcarchive += "PRODUCT_BUNDLE_IDENTIFIER=\"" + bundleid + "\" "

    os_ret = os.system(str_create_xcarchive)
    if os_ret == 2:
        print "\n [Ctrl + C] 您终止了打包过程!"
        sys.exit(2)

    # build ipa
    print ("正在生成ipa文件...")
    os_ret = os.system("xcodebuild -exportArchive -archivePath " + "\"" + cur_xcarchive + "\" " +
                       "-exportPath " + "\"" + cur_ipa + "\" -exportProvisioningProfile \"" + sign_info[2] + "\"")
    if os_ret == 2:
        print "\n [Ctrl + C] 您终止了打包过程!"
        sys.exit(2)

    if os.path.isfile(cur_ipa):
        print "[build succeed]:" + cur_ipa
    else:
        print ("貌似出什么问题了!!!")


def build():
    if len(sys.argv) == 4 and sys.argv[1] == "all":
        sign_name = sys.argv[2]
        version = sys.argv[3]
        
        print "-------------"
        print "all"
        print sign_name
        print version
        print "-------------"
        
        if sign_name not in signs:
            print "[签名配置错误] 请修改配置！"
            return

        print "开始打包所有平台!"
        for k in plists:
            if not os.path.isfile(plists[k][1]):
                print "[plist 配置错误]：" + plists[k][1]
                return

        # clean the all targets
        print "正在清理所有工程..."
        os_ret = os.system("xcodebuild clean -configuration Release -alltargets")
        if os_ret == 2:
            print "\n [Ctrl + C] 您终止了打包过程!"
            sys.exit(2)
    
        for k in plists:
            build_target(k, plists[k][0], signs[sign_name], plists[k][1], version)
        print "所有平台均打包完毕，请手动检查错误!"
        return

    if len(sys.argv) < 5:
        print "［参数错误］用法：python build-ios.py uc inhouse 3.3.0 com.wanmei.mini.condor.uc"
        return

    target = sys.argv[1]
    sign_name = sys.argv[2]
    version = sys.argv[3]
    bundleid = sys.argv[4]

    print "-------------"
    print target
    print sign_name
    print version
    print bundleid
    print "-------------"
    
    if sign_name not in signs:
        print "[签名配置错误] 请修改配置！"
        return
    if target not in plists:
        print "[target 错误] 请修改配置！"
        return
    if not os.path.isfile(plists[target][1]):
        print "[plist 配置错误]：" + plists[target][1]
        return

    # clean the specific target
    print "正在清理[" + target + "]工程..."
    os_ret = os.system("xcodebuild clean -configuration Release -target " + plists[target][0])
    if os_ret == 2:
        print "\n [Ctrl + C] 您终止了打包过程!"
        sys.exit(2)

    build_target(target, plists[target][0], signs[sign_name], plists[target][1], version, bundleid)
   
build()
